package cn.e2win.biz.menu;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.e2win.base.entity.SysFunction;
import cn.e2win.base.entity.SysMenu;
import cn.e2win.base.entity.SysUser;
import cn.e2win.biz.security.DmsGrantedFunction;
import cn.e2win.biz.security.UserSession;
import cn.e2win.biz.user.UserService;



@Controller
@Scope("request")
public class InitPageController {
	static Log logger = LogFactory.getLog(InitPageController.class);

	@Autowired
	private UserService userService;
	
	@Autowired
	private MenuService menuService;
	private static final String INIT = "/initPage";
	
	@RequestMapping(value=INIT)
	@ResponseBody
	public ModelAndView login(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		
		System.err.println("from=====" + request.getParameter("from"));
		
		
		Authentication  authentication =  SecurityContextHolder.getContext().getAuthentication();
		Collection<DmsGrantedFunction> grantedAuthority = (Collection<DmsGrantedFunction>)authentication.getAuthorities();
		SysUser user = (SysUser)authentication.getPrincipal();
		Map<String, Object> userDetail = userService.getUserForSession(user.getId());
		userDetail.put("myIndexTitle", "未完成销售订单追踪");
		userDetail.put("myIndexUrl", "order/sale/track.do?funId=123");

        String os = request.getHeader("user-agent");
        userDetail.put("isWindows", os.indexOf("Windows")>-1?true:false);
        userDetail.put("os", os);
        System.err.println("OS=====" + os);
        SysUser sessionUser = UserSession.getUser(user.getId());
		request.getSession().setAttribute("USER",userDetail);
		//给分页用，临时解决方案
		request.getSession().setAttribute("user", sessionUser);
		
		user.setCoId((Integer)userDetail.get("coId"));
		String url = "main";
/*		if("mobile".equals(sessionUser.getLoginFrom())){
			url ="redirect:/m/toLogin.do?account="+userDetail.get("account")+"&password="+userDetail.get("password");
		}*/
		ModelAndView mView = new ModelAndView(url);
		//String loginType = (String)request.getSession().getAttribute(MyUsernamePasswordAuthenticationFilter.LOGINTYPE);
		/*if (MyUsernamePasswordAuthenticationFilter.LOGINTYPE_MOBILE.equals(loginType)) {
			SysUser user = BaseController.getContextUser();
			LoginUser resultJosn = new LoginUser();
			resultJosn.setLoginMsg("login success");
			resultJosn.setSuccess(true);
			resultJosn.setUserId(user.getId());
			resultJosn.setUserName(user.getUsername());
			resultJosn.setMenuList(getMenus(grantedAuthority));
			
			mView.addObject(resultJosn);
		}else {*/
			modelMap.put("menuList",getMenus(grantedAuthority));
		//}
		return mView;
	}
	
	private List<SysMenu> getMenus(Collection<DmsGrantedFunction> grantedAuthority){
		List<SysMenu> menuList = menuService.getAll();
		Collections.sort(menuList);
		for (SysMenu menu: menuList) {
			
			ArrayList<SysFunction> functionList = new ArrayList<SysFunction>();
			menu.setFunctionList(functionList);
			
			for(DmsGrantedFunction gFunction : grantedAuthority){
				SysFunction function = gFunction.getFunction();
				if(function !=null && menu.getId().equals(function.getMenu().getId()) && function.getActiveStatusInt()==1){
					menu.setHasItems(true);
					if(function.getUrl().indexOf("funId=")<0){
						if(function.getUrl().indexOf("?")>0){
							function.setUrl(function.getUrl());//+"&funId=" + function.getId()
						}else{
							function.setUrl(function.getUrl());//+"?funId=" + function.getId()
						}
					}
					functionList.add(function);
				}
			}
			Collections.sort(functionList);
		}
		return menuList;
	}
	
}
